package com.aoxin.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie 工具类
 * 
 * @author lop
 * @date 2018年5月14日 下午4:23:14
 */
public class CookieUtil {

	public static String COOKIE_NAME = "slfCookie";

	/**
	 * 获取一个cookie 对象
	 * 
	 * @param name
	 * @return
	 */
	public static Cookie getCookie(String name) {
		Cookie cookie = null;
		Cookie[] cookies = ThreadLocalUtil.getRequest().getCookies();
		if (null != cookies) {
			for (Cookie coo : cookies) {
				if (name.equals(coo.getName())) {
					cookie = coo;
					break;
				}
			}
		}
		return cookie;
	}

	public static HttpServletResponse saveCookie(String name, String token) {
		Cookie cookie = new Cookie(name, token);
		cookie.setPath("/");
		HttpServletResponse resp = null;
		try {
			URLEncoder.encode(token, "utf-8");
			cookie.setMaxAge(5 * 365 * 24 * 60 * 60);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		resp = ThreadLocalUtil.getResponse();
		resp.addCookie(cookie);
		return resp;
	}

}
